<?php
class itemAction extends backendAction {
    public function _initialize() {
        parent::_initialize();
        $this->_mod = D('goods');
        //$this->_mod = D('item');
        $this->_cate_mod = D('item_cate');
        $brandlist= $this->_brand=M('brandlist')->where('status=1')->order('ordid asc,id asc')->select();
        $this->assign('brandlist',$brandlist);
    }

	private function showSelect($str0, $str1){
		$s1 = 33;
		$s2 = 66;
		$ref = '';
		if($str1 == 1){
			$sMin = 0;
			$sMax = $s1;
		}
		if($str1 == 2){
			$sMin = $s1;
			$sMax = $s2;
		}
		if($str1 == 3){
			$sMin = $s2;
			$sMax = 100;
		}
		if($str0>$sMin && $str0<=$sMax){
			$ref = ' selected ';
		}else{
			$ref = '';
		}
		return $ref;
	}
	
	public function index() {
		import("ORG.Util.Page");
		$item_goods = M('goods');
		$pc = 10;
		$count = $item_goods->count('id');
        $pager = new Page($count, $pc);
        $select = $item_goods->order('orderby DESC, id DESC');
        $select->limit($pager->firstRow.','.$pager->listRows);
        $page = $pager->show();
		$list = $select->select();

		$res = $this->_cate_mod->field('id,name,pid')->select();
        $cate_list = array();
        foreach ($res as $val) {
            $cate_list[$val['id']] = $val;
        }

        $this->assign('cate_list', $cate_list);

		$this->assign('page', $page);
		$this->assign('list', $list);
		$this->display();
	}

    public function add() {
    	
        if (IS_POST) {
			$goods = M('goods');
			
			$do_data = array();
			$orderby = $this->_request('orderby', 'trim');
			if(!$orderby)
				$this->error('请填写排序号');
			$do_data['orderby'] = $orderby;
			$cate_id = $this->_request('cate_id', 'trim');
			if(!$cate_id)
				$this->error('请选择商品类别');
			$do_data['cid'] = $cate_id;
			$title = $this->_request('title', 'trim');
			if(!$title)
				$this->error('请输入商品名称');
			$do_data['title'] = $title;
			$fbt = $this->_request('fbt', 'trim');
			if(!$fbt)
				$this->error('请输入副标题');
			$do_data['fbt'] = $fbt;
			$houdu = $this->_request('houdu', 'trim');
			if(!$houdu)
				$this->error('请输入厚度');
			$do_data['houdu'] = $houdu;
			$naigua = $this->_request('naigua', 'trim');
			if(!$naigua)
				$this->error('请输入耐刮');
			$do_data['naigua'] = $naigua;

			$geredu = $this->_request('geredu', 'trim', 100);
			if(!is_numeric($geredu) || $geredu<0 || $geredu>100)
				$this->error('请输入隔热度');
			$do_data['geredu'] = $geredu;
			$touguangdu = $this->_request('touguangdu', 'trim', 100);
			if(!is_numeric($touguangdu) || $touguangdu<0 || $touguangdu>100)
				$this->error('请输入透光度');
			$do_data['touguangdu'] = $touguangdu;

            //一键下拉选项
            $do_data['gere_level'] = $this->_request('gere_level', 'trim', 100);
            $do_data['touguang_level'] = $this->_request('touguang_level', 'trim', 100);
            $do_data['simidu'] = $this->_request('simidu', 'trim', 100);
            $do_data['xiaoshoujia'] = $this->_request('xiaoshoujia', 'trim', 100);
            $do_data['jianglie'] = $this->_request('jianglie', 'trim', 100);
            $do_data['qingxidu'] = $this->_request('qingxidu', 'trim', 100);

			$fangshai = $this->_request('fangshai', 'trim', 100);
			if(!is_numeric($fangshai) || $fangshai<0 || $fangshai>100)
				$this->error('请输入防晒指数');
			$do_data['fangshai'] = $fangshai;

			$description = $this->_request('description', 'trim');
			if(!$description)
				$this->error('请输入描述');
			$do_data['description'] = $description;

			$price = $this->_request('price', 'trim');
			if(!$price)
				$this->error('请输入商品价格');
			$do_data['price'] = $price;

            //适用范围
            $syfw = $this->_request('syfw', 'trim');
            $do_data['syfw'] = $syfw;
			
            $jianglimax = $this->_request('jianglimax', 'trim');
			$jianglimax = '0.00' ;
			if(!$jianglimax)
				$this->error('请输入最高奖励');
			$do_data['jianglimax'] = $jianglimax;
			
			$goods_stock = $this->_request('goods_stock', 'trim');
			if(!$goods_stock)
				$this->error('请输入商品库存');
			$do_data['num'] = $goods_stock;
			$news = $this->_request('news', 'trim')=='on'?1:0;
			$do_data['new'] = $news;
			$tuijian = $this->_request('tuijian', 'trim')=='on'?1:0;
			$do_data['hot'] = $tuijian;
			$xingneng = $this->_request('xingneng', 'trim');
			if(!$xingneng)
				$this->error('请输入性能');
			
			$do_data['xingneng'] = $xingneng;
			$wudu = $this->_request('wudu', 'trim');
            $do_data['wudu'] = $wudu;
			
			$do_data['add_time'] = time();
			$do_data['status'] = 1;

            $uf = new UploadFile();
            if($uf->upload('./data/upload/item/')) {
                $info = $uf->getUploadFileInfo();
                if(count($info) > 0) {
                    $file = $info[0];
                    $do_data['img'] = $file['savepath'] . $file['savename'];
                }
            } else {
                $this->error('请确认上传图片：' . $uf->getErrorMsg());
            }
			
			$ref = $goods->add($do_data);
			
			if($ref)
				$this->success(L('operation_success'), U('index', array('menuid' => 52)));
			else
				$this->error(L('operation_failure'));
        } else {
            //模板数据
            $Config = M('config');
            $tpl = $Config->where('name="goods_tpl"')->find();

            if($tpl) {
                $item = json_decode($tpl['content'], true);
                //分类
                $spid = $this->_cate_mod->where(array('id'=>$item['cid']))->getField('spid');
                if( $spid == 0 ){
                    $spid = $item['cid'];
                }else{
                    $spid .= $item['cid'];
                }
                $this->assign('selected_ids',$spid); //分类选中
                $tag_cache = unserialize($item['tag_cache']);
                $item['tags'] = implode(' ', $tag_cache);
                //一键下单条件筛选
                $selects = array(
                    'touguang_level' => '透光性',
                    // 'simidu' => '私密度',
                    'gere_level' => '隔热率',
                    'xiaoshoujia' => '销售价'
                    // 'jianglie' => '奖励额',
                );

                $this->assign('selects', $selects);

                $this->assign('info', $item);
                //相册
                $img_list = M('item_img')->where(array('item_id'=>$item->id))->select();
                $this->assign('img_list', $img_list);
            }

            $this->display();
        }
    }
	
	public function delete() {
		$res = array();
		$res['status'] = 0;
		$res['msg'] = "未知错误";
		$res['data'] = "";
		$res['dialog'] = "";
		
		$id = $this->_get('id', 'intval');
		$id = $id?$id:0;
		$item = $this->_mod->where(array('id'=>$id))->find();
		if($item){
			$ref = $this->_mod->where(array('id'=>$id))->delete();
			if($ref){
				$res['status'] = 1;
				$res['msg'] = "删除成功";
			}else{
				$res['msg'] = "删除失败";
			}
		}
		
		echo json_encode($res);
		exit;
	}

    public function edit() {
        if (IS_POST) {
            $goods = M('goods');
			$id = $this->_post('id', 'intval');
			$do_data = array();
			$orderby = $this->_request('orderby', 'trim');
			if(!$orderby)
				$this->error('请输入排序号');
			$do_data['orderby'] = $orderby;
			$cate_id = $this->_request('cate_id', 'trim');
			if(!$cate_id)
				$this->error('请选择商品类别');
			$do_data['cid'] = $cate_id;
			$title = $this->_request('title', 'trim');
			if(!$title)
				$this->error('请输入商品名称');
			$do_data['title'] = $title;
			$fbt = $this->_request('fbt', 'trim');
			if(!$fbt)
				$this->error('请输入副标题');
			$do_data['fbt'] = $fbt;
			$houdu = $this->_request('houdu', 'trim');
			if(!$houdu)
				$this->error('请输入厚度');
			$do_data['houdu'] = $houdu;
			$naigua = $this->_request('naigua', 'trim');
			if(!$naigua)
				$this->error('请输入耐刮');
			$do_data['naigua'] = $naigua;

            //一键下拉选项
            $do_data['gere_level'] = $this->_request('gere_level', 'trim', 100);
            $do_data['touguang_level'] = $this->_request('touguang_level', 'trim', 100);
            $do_data['simidu'] = $this->_request('simidu', 'trim', 100);
            $do_data['xiaoshoujia'] = $this->_request('xiaoshoujia', 'trim', 100);
            $do_data['jianglie'] = $this->_request('jianglie', 'trim', 100);
            $do_data['qingxidu'] = $this->_request('qingxidu', 'trim', 100);

			$geredu = $this->_request('geredu', 'trim', 100);
			if(!is_numeric($geredu) || $geredu<0 || $geredu>100)
				$this->error('请输入隔热度');
			$do_data['geredu'] = $geredu;
			$touguangdu = $this->_request('touguangdu', 'trim', 100);
			if(!is_numeric($touguangdu) || $touguangdu<0 || $touguangdu>100)
				$this->error('请输入透光度');
			$do_data['touguangdu'] = $touguangdu;

			$fangshai = $this->_request('fangshai', 'trim', 100);
			if(!is_numeric($fangshai) || $fangshai<0 || $fangshai>100)
				$this->error('请输入防晒指数');
			$do_data['fangshai'] = $fangshai;

			$syfw = $this->_request('syfw', 'trim');
			if(!$syfw)
				$this->error('请输入适用范围');
			$do_data['syfw'] = $syfw;
			
			$description = $this->_request('description', 'trim');
			if(!$description)
				$this->error('请输入描述');
			$do_data['description'] = $description;
			$price = $this->_request('price', 'trim');
			if(!$price)
				$this->error('请输入商品价格');
			$do_data['price'] = $price;
			
            $jianglimax = $this->_request('jianglimax', 'trim');
			$jianglimax = '0.00' ;
			if(!$jianglimax)
				$this->error('请输入最高奖励');
			$do_data['jianglimax'] = $jianglimax;
			
			$goods_stock = $this->_request('goods_stock', 'trim');
			if(!$goods_stock)
				$this->error('请输入商品库存');
			$do_data['num'] = $goods_stock;
			$news = $this->_request('news', 'trim')=='on'?1:0;
			$do_data['new'] = $news;
			$tuijian = $this->_request('tuijian', 'trim')=='on'?1:0;
			$do_data['hot'] = $tuijian;
			$xingneng = $this->_request('xingneng', 'trim');
			if(!$xingneng)
				$this->error('请输入性能');
			
			$do_data['xingneng'] = $xingneng;
			$wudu = $this->_request('wudu', 'trim');
			if(is_array($wudu))
				$do_data['wudu'] = implode('|', $wudu);
			else
				$do_data['wudu'] = $wudu;
			
			$do_data['updatatime'] = time();

            $uf = new UploadFile();
            if($uf->upload('./data/upload/item/')) {
                $info = $uf->getUploadFileInfo();
                if(count($info) > 0) {
                    $file = $info[0];
                    $do_data['img'] = $file['savepath'] . $file['savename'];
                }
            }


			$ref = $goods->where(array('id'=>$id))->save($do_data);
			
			if($ref)
				$this->success(L('operation_success'), U('index', array('menuid' => 52)));
			else
				$this->error(L('operation_failure'));
        } else {
            $id = $this->_get('id','intval');
            $item = $this->_mod->where(array('id'=>$id))->find();
            //分类
            $spid = $this->_cate_mod->where(array('id'=>$item['cid']))->getField('spid');
            if( $spid==0 ){
                $spid = $item['cid'];
            }else{
                $spid .= $item['cid'];
            }
            $this->assign('selected_ids',$spid); //分类选中
            $tag_cache = unserialize($item['tag_cache']);
            $item['tags'] = implode(' ', $tag_cache);

            //一键下单选项
            $selects = array(
                'touguang_level' => '透光性',
                // 'simidu' => '私密度',
                'gere_level' => '隔热率',
                'xiaoshoujia' => '销售价'
                // 'jianglie' => '奖励额',
            );

            $this->assign('selects', $selects);


            $this->assign('info', $item);
           
            //相册
            $img_list = M('item_img')->where(array('item_id'=>$id))->select();
            $this->assign('img_list', $img_list);
           
            $this->display();
        }
    }

    function delete_album() {
        $album_mod = M('item_img');
        $album_id = $this->_get('album_id','intval');
        $album_img = $album_mod->where('id='.$album_id)->getField('url');
        if( $album_img ){
            $ext = array_pop(explode('.', $album_img));
            $album_min_img = C('pin_attach_path') . 'item/' . str_replace('.' . $ext, '_s.' . $ext, $album_img);
            is_file($album_min_img) && @unlink($album_min_img);
            $album_img = C('pin_attach_path') . 'item/' . $album_img;
            is_file($album_img) && @unlink($album_img);
            $album_mod->delete($album_id);
        }
        echo '1';
        exit;
    }

    function delete_attr() {
        $attr_mod = M('item_attr');
        $attr_id = $this->_get('attr_id','intval');
        $attr_mod->delete($attr_id);
        echo '1';
        exit;
    }

    /**
     * 商品审核
     */
    public function check() {
        //分类信息
        $res = $this->_cate_mod->field('id,name')->select();
        $cate_list = array();
        foreach ($res as $val) {
            $cate_list[$val['id']] = $val['name'];
        }
        $this->assign('cate_list', $cate_list);
        //商品信息
        //$map = $this->_search();
        $map=array();
        $map['status']=0;
        ($time_start = $this->_request('time_start', 'trim')) && $map['add_time'][] = array('egt', strtotime($time_start));
        ($time_end = $this->_request('time_end', 'trim')) && $map['add_time'][] = array('elt', strtotime($time_end)+(24*60*60-1));
        $cate_id = $this->_request('cate_id', 'intval');
        if ($cate_id) {
            $id_arr = $this->_cate_mod->get_child_ids($cate_id, true);
            $map['cate_id'] = array('IN', $id_arr);
            $spid = $this->_cate_mod->where(array('id'=>$cate_id))->getField('spid');
            if( $spid==0 ){
                $spid = $cate_id;
            }else{
                $spid .= $cate_id;
            }
        }
        ($keyword = $this->_request('keyword', 'trim')) && $map['title'] = array('like', '%'.$keyword.'%');
        $this->assign('search', array(
            'time_start' => $time_start,
            'time_end' => $time_end,
            'selected_ids' => $spid,
            'cate_id' => $cate_id,
            'keyword' => $keyword,
        ));
        //分页
        $count = $this->_mod->where($map)->count('id');
        $pager = new Page($count, 20);
        $select = $this->_mod->field('id,title,img,cate_id')->where($map)->order('id DESC');
        $select->limit($pager->firstRow.','.$pager->listRows);
        $page = $pager->show();
        $this->assign("page", $page);
        $list = $select->select();
        foreach ($list as $key=>$val) {
            $tag_list = unserialize($val['tag_cache']);
            $val['tags'] = implode(' ', $tag_list);
            $list[$key] = $val;
        }
        $this->assign('list', $list);
        $this->assign('list_table', true);
        $this->display();
    }

    /**
     * 审核操作
     */
    public function do_check() {
        $mod = D($this->_name);
        $pk = $mod->getPk();
        $ids = trim($this->_request($pk), ',');
        $datas['id']=array('in',$ids);
        $datas['status']=1;
        if ($datas) {
            if (false !== $mod->save($datas)) {
                IS_AJAX && $this->ajaxReturn(1, L('operation_success'));
            } else {
                IS_AJAX && $this->ajaxReturn(0, L('operation_failure'));
            }
        } else {
            IS_AJAX && $this->ajaxReturn(0, L('illegal_parameters'));
        }

    }

    /**
     * ajax获取标签
     */
    public function ajax_gettags() {
        $title = $this->_get('title', 'trim');
        $tag_list = D('tag')->get_tags_by_title($title);
        $tags = implode(' ', $tag_list);
        $this->ajaxReturn(1, L('operation_success'), $tags);
    }

    public function delete_search() {
        $items_mod = D('item');
        $items_cate_mod = D('item_cate');
        $items_likes_mod = D('item_like');
        $items_pics_mod = D('item_img');
        $items_tags_mod = D('item_tag');
        $items_comments_mod = D('item_comment');

        if (isset($_REQUEST['dosubmit'])) {
            if ($_REQUEST['isok'] == "1") {
                //搜索
                $where = '1=1';
                $keyword = trim($_POST['keyword']);
                $cate_id = trim($_POST['cate_id']);
                $cate_id = trim($_POST['cate_id']);
                $time_start = trim($_POST['time_start']);
                $time_end = trim($_POST['time_end']);
                $status = trim($_POST['status']);
                $min_price = trim($_POST['min_price']);
                $max_price = trim($_POST['max_price']);
                $min_rates = trim($_POST['min_rates']);
                $max_rates = trim($_POST['max_rates']);

                if ($keyword != '') {
                    $where .= " AND title LIKE '%" . $keyword . "%'";
                }
                if ($cate_id != ''&&$cate_id!=0) {
                    $where .= " AND cate_id=" . $cate_id;
                }
                if ($time_start != '') {
                    $time_start_int = strtotime($time_start);
                    $where .= " AND add_time>='" . $time_start_int . "'";
                }
                if ($time_end != '') {
                    $time_end_int = strtotime($time_end);
                    $where .= " AND add_time<='" . $time_end_int . "'";
                }
                if ($status != '') {
                    $where .= " AND status=" . $status;
                }
                if ($min_price != '') {
                    $where .= " AND price>=" . $min_price;
                }
                if ($max_price != '') {
                    $where .= " AND price<=" . $max_price;
                }
                if ($min_rates != '') {
                    $where .= " AND rates>=" . $min_rates;
                }
                if ($max_rates != '') {
                    $where .= " AND rates<=" . $max_rates;
                }
                $ids_list = $items_mod->where($where)->select();
                $ids = "";
                foreach ($ids_list as $val) {
                    $ids .= $val['id'] . ",";
                }
                if ($ids != "") {
                    $ids = substr($ids, 0, -1);
                    $items_likes_mod->where("item_id in(" . $ids . ")")->delete();
                    $items_pics_mod->where("item_id in(" . $ids . ")")->delete();
                    $items_tags_mod->where("item_id in(" . $ids . ")")->delete();
                    $items_comments_mod->where("item_id in(" . $ids . ")")->delete();
                    M('album_item')->where("item_id in(" . $ids . ")")->delete();
                    M('item_attr')->where("item_id in(" . $ids . ")")->delete();

                }
                $items_mod->where($where)->delete();

                //更新商品分类的数量
                $items_nums = $items_mod->field('cate_id,count(id) as items')->group('cate_id')->select();
                foreach ($items_nums as $val) {
                    $items_cate_mod->save(array('id' => $val['cate_id'], 'items' => $val['items']));
                    M('album')->save(array('cate_id' => $val['cate_id'], 'items' => $val['items']));
                }

                $this->success('删除成功', U('item/delete_search'));
            } else {
                $this->success('确认是否要删除？', U('item/delete_search'));
            }
        } else {
            $res = $this->_cate_mod->field('id,name')->select();

            $cate_list = array();
            foreach ($res as $val) {
                $cate_list[$val['id']] = $val['name'];
            }
            //$this->assign('cate_list', $cate_list);
            $this->display();
        }
    }

    /**
     * 设置商品模板
     */
    public function setTemplate() {
        $itemId = $_GET['item'];
        $item_goods = M('goods');
        $item = $item_goods->where(array('id'=>$itemId))->find();

        unset($item['img']);

        $content = json_encode($item);

        $Config = M('config');
        $tpl = $Config->where('name="goods_tpl"')->find();
        if($tpl) {
            $Config->where("id=" . $tpl['id'])->save(array('content' => $content));
        } else {
            $Config->data(array('content' => $content, 'name' => 'goods_tpl'))->add();
        }

        $this->success('设置成功');
    }
}